<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="126px">
      <div class="flex justify-between">
        <div class="w-50%">
          <el-form-item :label="t('video.video_title')" prop="video_title">
            <el-input v-model="form.video_title" clearable :placeholder="t('video.video_title')" />
          </el-form-item>
          <el-form-item :label="t('video.youtube_vid')" prop="youtube_vid">
            <el-input
              v-model="form.youtube_vid"
              clearable
              :disabled="videoList.length >= 1"
              maxlength="32"
              :placeholder="t('video.youtube_vid')"
            />
          </el-form-item>
          <el-form-item :label="t('video.category')" prop="category">
            <el-select
              v-model="form.category"
              :filterable="true"
              :placeholder="t('video.category')"
              :clearable="false"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="t('productMerge.productname')" prop="productname">
            <div class="w-full flex items-center">
              <el-select-v2
                v-model="form.pm_ids"
                :options="productMergeOptions"
                :props="{ label: 'productname', value: 'id' }"
                multiple
                clearable
                filterable
                @change="handleProductMergeChange"
              />
              <el-button type="primary" @click="handleOpenProductMerge" class="ml-2"
                >选择</el-button
              >
            </div>
          </el-form-item>

          <el-form-item :label="t('video.blogger_name')" prop="youtube_vid">
            <el-input
              v-model="form.blogger_name"
              clearable
              :disabled="videoList.length >= 1"
              maxlength="32"
              :placeholder="t('video.blogger_name')"
            />
          </el-form-item>
          <el-form-item :label="t('video.publish_time')" class="w-60%" prop="publish_time">
            <el-date-picker
              v-model="form.publish_time"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :placeholder="'请选择' + t('video.publish_time')"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item :label="t('video.sort')" prop="sort">
            <el-input v-model="form.sort" clearable :placeholder="t('video.sortMsg')" />
          </el-form-item>

          <!-- 新增：封面图片上传 -->
          <el-form-item :label="t('video.coverimage_id')" prop="coverimage_id">
            <UploadFileComponent
              v-model:file-list="coverList"
              url="/common/uploadFile"
              upload-file-button-name="上传封面"
              :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
              :params="{ directory: 9 }"
              :limit="1"
              list-type="picture"
              :show-file-list="true"
              @upload-success-res="handleUploadCallbackForImg"
              @handle-remove-file="handleRemoveFileForCover"
            />
          </el-form-item>

          <!-- 修改：视频上传方式 -->
          <el-form-item :label="t('video.video_upload')" prop="video_id">
            <el-button type="primary" :disabled="!!form.youtube_vid" @click="uploadVideo()"
              >上传视频</el-button
            >
            <!-- 显示已上传的视频文件名 -->
            <div v-if="videoList.length" class="ml-2 text-sm">
              {{ videoList[0]?.name || '已上传视频' }}
            </div>
          </el-form-item>
        </div>
        <div class="w-50%">
          <el-form-item :label="t('video.init_shownumber')" prop="init_shownumber">
            <el-input
              v-model="form.init_shownumber"
              type="number"
              clearable
              :placeholder="t('video.init_shownumber')"
            />
          </el-form-item>
          <el-form-item :label="t('video.showstate')">
            <el-switch
              v-model="form.showstate"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              active-text="对外显示"
              inactive-text="不对外显示"
            />
          </el-form-item>

          <el-form-item :label="t('video.pmv_id')" prop="pmv_id">
            <div class="w-full flex items-center">
              <el-select-v2
                :key="`pmv-${selectKey}`"
                v-model="form.pmv_id"
                :options="productMergePmvOptions"
                :props="{ label: 'productname', value: 'id' }"
                multiple
                clearable
                filterable
                @change="handlePmvIdChange"
              />
              <el-button type="primary" @click="handleOpenPmvId" class="ml-2">选择</el-button>
            </div>
          </el-form-item>

          <el-form-item :label="t('video.smv_id')" prop="smv_id">
            <div class="w-full flex items-center">
              <el-select-v2
                :key="`smv-${selectKey}`"
                v-model="form.smv_id"
                :options="productMergeSmvOptions"
                :props="{ label: 'productname', value: 'id' }"
                multiple
                clearable
                filterable
                @change="handleSmvIdChange"
              />
              <el-button type="primary" @click="handleOpenSmvId" class="ml-2">选择</el-button>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
  </ContentDetailWrap>

  <UploadDialog ref="DialogUploadRef" @expose-upload-data="exposeUploadData" />

  <!--  选择聚合商品弹框-->
  <ProductMerge
    ref="DialogProductMergeCheckedRef"
    @expose-multiple-data="getExposeProductMergeData"
    :multiple="true"
  />

  <!--  选择聚合商品的商品主视频弹框-->
  <ProductMerge
    ref="DialogPmvIDCheckedRef"
    @expose-multiple-data="getExposePmvIdData"
    :multiple="true"
  />

  <!--  选择聚合商品的商品副视频弹框-->
  <ProductMerge
    ref="DialogSmvIDCheckedRef"
    @expose-multiple-data="getExposeSmvIdData"
    :multiple="true"
  />
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadFile,
  type UploadFiles,
  type UploadProps
} from 'element-plus'
import { getEnumApi, getInfoApi, editDataApi } from '@/api/market/VideoManage'
import { getListApi } from '@/api/productMerge'
import UploadDialog from '@/views/Market/VideoManage/components/DialogUpload/index.vue'
import ProductMerge from '@/components/Dialog/src/ProductMerge/Index.vue'
import UploadFileComponent from '@/components/UploadFile/index.vue' // 重命名

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()

const loading = ref<boolean>(false)

const modelList = ref<Array<Record<string, any>>>([])
const categoryList = ref<Array<Record<string, any>>>([])

const DialogUploadRef = ref<InstanceType<typeof UploadDialog>>()

// 新增：封面和视频列表
const coverList = ref<any[]>([]) // 封面图片列表
const videoList = ref<any[]>([]) // 视频文件列表

interface FileItem {
  uid: number
  name: string
  url: string
  type: string
  id: string
}

const productMergeOptions = ref<any[]>([])
const productMergePmvOptions = ref<any[]>([])
const productMergeSmvOptions = ref<any[]>([])

// 添加一个响应式key来强制重新渲染组件
const selectKey = ref(0)

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  video_title: '',
  video_id: '',
  model_id: '',
  youtube_vid: '',
  coverimage_id: '', // 确保表单中有封面ID字段
  pm_ids: [],
  category: '',
  sort: '',
  publish_time: '',
  blogger_name: '',
  showstate: '',
  init_shownumber: '',
  pmv_id: [],
  smv_id: []
})
const rules = ref<FormRules>({
  video_title: [
    {
      required: true,
      message: t('video.titleMsg'),
      trigger: 'change'
    }
  ],
  model_id: [
    {
      required: true,
      message: t('video.modelMsg'),
      trigger: 'change'
    }
  ]
})

// 封面图片上传成功回调
const handleUploadCallbackForImg = (val: any) => {
  coverList.value = [val] // 只能上传一个封面
  form.value.coverimage_id = val.id
}

// 封面图片删除回调
const handleRemoveFileForCover = () => {
  coverList.value = []
  form.value.coverimage_id = ''
}

// 视频上传处理
const uploadVideo = () => {
  nextTick(() => {
    DialogUploadRef.value!.dialogVisible = true
    // 传入当前视频列表用于编辑
    DialogUploadRef.value?.getBackShow(videoList.value)
  })
}

// 处理弹框返回的视频数据
const exposeUploadData = (list: FileItem[]) => {
  videoList.value = list
  if (list.length > 0) {
    form.value.video_id = list[0].id
  }
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 检查视频：要么上传视频，要么填写YouTube ID
      if (!form.value.video_id && !form.value.youtube_vid) {
        ElMessage.error('请上传视频或填写YouTube视频ID')
        return
      }

      // 处理pm_ids
      const data = { ...form.value }
      if (Array.isArray(data.pm_ids) && data.pm_ids.length > 0) {
        data.pm_ids = data.pm_ids.join(',')
      } else {
        data.pm_ids = ''
      }
      data.id = query.id
      const resp = await editDataApi(data)
      if (resp.code === 0) {
        ElMessage.success(t('common.updateSucMsg'))
        push({ path: '/market/videoManage' })
      }
    }
  })
}

// 聚合商品弹框 组件方法 start
const DialogProductMergeCheckedRef = ref<InstanceType<typeof ProductMerge>>()

const handleOpenProductMerge = () => {
  nextTick(() => {
    if (!DialogProductMergeCheckedRef.value) return
    DialogProductMergeCheckedRef.value.dialogVisible = true
    console.log(form.value.pm_ids)
    DialogProductMergeCheckedRef.value.initialize(
      form.value.pm_ids ? form.value.pm_ids.map((item: any) => ({ id: item })) : []
    )
  })
}

const getExposeProductMergeData = (val: any[]) => {
  if (!val || !val.length) return

  // 聚合商品需要保留原有的选中项并合并新选择的项
  // 因为API返回的 pm_names 包含了原始的选中商品信息
  const existingSelected = productMergeOptions.value || []
  const newSelected = val.filter(
    (item) => !existingSelected.some((existing) => existing.id === item.id)
  )

  // 合并原有选中的和新选择的商品
  productMergeOptions.value = [...existingSelected, ...newSelected]

  nextTick(() => {
    form.value.pm_ids = productMergeOptions.value.map((item: any) => item.id)
  })
}

const handleProductMergeChange = (val: any[]) => {
  form.value.pm_ids = val
}
//  组件方法 end

// 聚合商品的主视频弹框 组件方法 start
const DialogPmvIDCheckedRef = ref<InstanceType<typeof ProductMerge>>() // 定义弹框引用

const handleOpenPmvId = () => {
  nextTick(() => {
    if (!DialogPmvIDCheckedRef.value) return
    DialogPmvIDCheckedRef.value.dialogVisible = true
    const disabledVal = form.value.smv_id
      ? form.value.smv_id.map((item: any) => ({ id: item }))
      : [] // 商品副视频
    DialogPmvIDCheckedRef.value.initialize(
      form.value.pmv_id ? form.value.pmv_id.map((item: any) => ({ id: item })) : [],
      disabledVal
    )
  })
}

const getExposePmvIdData = (val: any[]) => {
  if (!val || !val.length) return
  // 更新选项列表为新选择的商品，这样组件能正确显示名称
  productMergePmvOptions.value = val
  nextTick(() => {
    form.value.pmv_id = val.map((item: any) => item.id)
  })
}

const handlePmvIdChange = (val: any[]) => {
  form.value.pmv_id = val
}
// end

// 聚合商品的商品副视频弹框 组件方法 start
const DialogSmvIDCheckedRef = ref<InstanceType<typeof ProductMerge>>() // 定义弹框引用

const handleOpenSmvId = () => {
  nextTick(() => {
    if (!DialogSmvIDCheckedRef.value) return
    DialogSmvIDCheckedRef.value.dialogVisible = true
    const disabledVal = form.value.pmv_id
      ? form.value.pmv_id.map((item: any) => ({ id: item }))
      : [] // 商品主视频
    DialogSmvIDCheckedRef.value.initialize(
      form.value.smv_id ? form.value.smv_id.map((item: any) => ({ id: item })) : [],
      disabledVal
    )
  })
}

const getExposeSmvIdData = (val: any[]) => {
  if (!val || !val.length) return
  // 更新选项列表为新选择的商品，这样组件能正确显示名称
  productMergeSmvOptions.value = val
  nextTick(() => {
    form.value.smv_id = val.map((item: any) => item.id)
  })
}

const handleSmvIdChange = (val: any[]) => {
  form.value.smv_id = val
}
// end

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  categoryList.value = resp.data.category
}

//获取回显数据 - 修复封面和视频回显问题
const getBackShow = async () => {
  const resp = await getInfoApi(query.id as string)
  if (!resp) return // 添加一个保护，防止 resp 未定义时JS报错
  console.log('API返回数据:', resp.data)

  // 设置 productMergeOptions，处理空值情况
  productMergeOptions.value = Array.isArray(resp.data.pm_names)
    ? resp.data.pm_names.map((item: any) => ({
        id: item.id,
        productname: item.productname,
        value: item.id,
        checked: true
      }))
    : []

  await nextTick()

  // 设置表单数据
  form.value = {
    video_title: resp.data.video_title,
    video_id: resp.data.video_id,
    model_id: resp.data.model_id,
    youtube_vid: resp.data.youtube_vid,
    coverimage_id: resp.data.coverimage_id,
    showstate: resp.data.showstate,
    init_shownumber: resp.data.init_shownumber,
    pm_ids: resp.data.pm_ids ? resp.data.pm_ids.split(',').map((id) => parseInt(id)) : [], // 处理 null 的情况
    blogger_name: resp.data.blogger_name,
    sort: resp.data.sort,
    publish_time: resp.data.publish_time,
    category: resp.data.category,
    pmv_id: resp.data.pmv_id ? resp.data.pmv_id : [],
    smv_id: resp.data.smv_id ? resp.data.smv_id : []
  }

  // 处理回显文件：分离封面和视频
  if (resp.data.file && Array.isArray(resp.data.file)) {
    // 修复：根据文件类型正确分离封面和视频
    const coverFiles = resp.data.file.filter((file) => file.type === 'image')
    const videoFiles = resp.data.file.filter((file) => file.type === 'video')

    coverList.value = coverFiles
    videoList.value = videoFiles

    console.log('封面文件列表:', coverList.value)
    console.log('视频文件列表:', videoList.value)
  }
}

const getProductMergeList = async () => {
  const resp = await getListApi({ pageIndex: 1, pageSize: 10000 })
  if (!resp?.data?.list) {
    console.error('未能获取聚合商品列表或列表为空。')
    return
  }
  const allProducts = resp.data.list

  // 将完整的商品列表提供给下拉框组件，让组件自行匹配ID和名称
  // 这样 el-select-v2 就能根据 v-model 的值找到对应的商品名称进行显示
  productMergePmvOptions.value = allProducts.filter((p) => form.value.pmv_id.includes(p.id))
  productMergeSmvOptions.value = allProducts.filter((p) => form.value.smv_id.includes(p.id))
}

onMounted(async () => {
  // 使用 await 保证 getBackShow 首先执行完毕，拿到回显数据和ID
  await getBackShow()
  // 然后再调用 getProductMergeList 来根据ID匹配商品名称
  await getProductMergeList()

  // 使用 nextTick 确保选项数据更新后再触发组件重新渲染
  await nextTick()

  // 强制重新渲染组件以显示正确的标签
  selectKey.value++

  // 最后获取其他下拉框信息
  getDropDownBoxInfo()
})
</script>
<style lang="less" scoped>
.media-container {
  display: flex;
  justify-content: space-between; /* 居中对齐内容之间的间隔 */
  flex-wrap: wrap; /* 允许内容换行以适应小屏幕 */
  gap: 20px; /* 控制图片和视频之间的间距 */
}

.media-item {
  flex: 0 1 calc(50% - 20px); /* 在容器中占据 50% 的空间，减去 gap */
  max-height: 400px;
  object-fit: cover; /* 保持图像比例 */
  margin-top: 20px;
}

.media-item img,
.media-item video {
  width: 100%;
  height: auto; /* 高度自适应，保持比例 */
}

.file-list-container {
  margin-top: 20px;
}

.el-upload-list {
  padding: 0;
  margin: 0;

  /* Optional adjustments for your layout */
  list-style: none;
}

.el-upload-list__item {
  display: flex;
  padding: 4px 8px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  align-items: center;
  justify-content: space-between;
}

.el-upload-list__item-name {
  flex-grow: 1;
  color: #606266;
  text-decoration: none;
}

.el-upload-list__item-name:hover {
  color: #409eff;
}

.el-icon-view,
.el-icon-delete {
  margin-left: 10px;
  color: #606266;
  cursor: pointer;
}

.el-icon-view:hover {
  color: #409eff;
}

.el-icon-delete:hover {
  color: #f56c6c;
}
</style>
